<?php

function addslashes_deep($value) {
    $value = is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    return $value;
}

function stripslashes_deep($value) {
    if (is_array($value)) {
        $value = array_map('stripslashes_deep', $value);
    } elseif (is_object($value)) {
        $vars = get_object_vars($value);
        foreach ($vars as $key => $data) {
            $value->{$key} = stripslashes_deep($data);
        }
    } else {
        $value = stripslashes($value);
    }

    return $value;
}

function todaytime() {
    return mktime(0, 0, 0, date('m'), date('d'), date('Y'));
}

/**
 * 友好时间
 */
function fdate($time) {
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}



function attach($attach, $type) {
    if (false === strpos($attach, 'http://')) {
        //本地附件
        return __ROOT__ . '/' . C('pin_attach_path') . $type . '/' . $attach;
        //远程附件
        //todo...
    } else {
        //URL链接
        return $attach;
    }
}

/**
 * 附件下载地址(如公告)
 * @param json $att
 * @param string $type
 * @return string
 */
function attUrl($json, $type) {
	$data = json_decode($json, true);
    if($data) {
		//本地附件
		return __ROOT__ . '/' . C('pin_attach_path') . $type . '/' . $data['savename'];
    }
}

/**
 * 附件名称
 * @param json $att
 * @return string
 */
function attName($json) {
	$data = json_decode($json, true);
    if($data) {
		//本地附件
		return $data['name'];
    }
}



/**
 * 对象转换成数组
 */
function object_to_array($obj) {
    $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
    foreach ($_arr as $key => $val) {
        $val = (is_array($val) || is_object($val)) ? object_to_array($val) : $val;
        $arr[$key] = $val;
    }
    return $arr;
}




/**
 * 根据半正失公式，获取两地理坐标之间的距离
 *
 * @param integer 坐标1经度
 * @param integer 坐标1纬度
 * @param integer 坐标2经度
 * @param integer 坐标2纬度
 * @return integer 两坐标之间的距离，以KM为单位
 */
function get_dist($lng1, $lat1, $lng2 ,$lat2)
{
	$r = 6371.137;
	$dlat = deg2rad($lat2 - $lat1);
	$dlng = deg2rad($lng2 - $lng1);
	 
	$a = pow(sin($dlat / 2), 2) +
	cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
	pow(sin($dlng / 2), 2);

	$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
	 
	return $r * $c;
}

function array_sort($array, $on, $order=SORT_ASC)
{
	$new_array = array();
	$sortable_array = array();

	if (count($array) > 0) {
		foreach ($array as $k => $v) {
			if (is_array($v)) {
				foreach ($v as $k2 => $v2) {
					if ($k2 == $on) {
						$sortable_array[$k] = $v2;
					}
				}
			} else {
				$sortable_array[$k] = $v;
			}
		}

		switch ($order) {
			case SORT_ASC:
				asort($sortable_array);
				break;
			case SORT_DESC:
				arsort($sortable_array);
				break;
		}

		foreach ($sortable_array as $k => $v) {
			$new_array[$k] = $array[$k];
		}
	}

	return $new_array;
}

/**
 * 
 * 将CSV文件读取到一个关联数组中
 * @param $file	文件路径（csv文件的编码必须为 ANSI）
 * @return array
 */
function csvToArray($file){
	if(!is_file($file)) return false;
	$res = fopen($file, "r"); 
	$head = fgetcsv($res);
	$arr = array();
	if($res){
		//打开csv中一行
		while($data = fgetcsv($res)){
			$num = count($data);
			for($i=0; $i<$num; $i++){
				$temp[iconv('gbk','utf-8',trim($head[$i]))] = iconv('gbk','utf-8',trim($data[$i]));
			}
			$arr[] = $temp;
		}
		fclose($res);
	} 
	return $arr;
}

/**
 * 
 * 将excel文件读取到一个关联数组中
 * @param $file	文件路径
 * @param $index 返回的数组是否为索引数组
 * @return array
 */
function excelToArray($file, $index=false){
	if(!is_file($file)) return false;
	import('@.ORG.Excel.ExcelReader');
	$reader = new Spreadsheet_Excel_Reader($file, false, '');
	$res = $reader->sheets[0]['cells'];unset($reader);
	if(is_array($res)){
		if($index){
			//返回索引数组
			foreach ($res[1] as $k=>$n){
				if($n == ''){
					unset($res[1][$k]);
				}
			}
			foreach ($res as $key=>&$n){
				for($i=1; $i<=count($res[1]); $i++){
					if(! isset($n[$i])){
						$arr[$key][$i] = '';
					}else{
						$arr[$key][$i] = trim($n[$i]); 
					}
				}
			}
		}else{
			//返回关联数组
			$head = $res[1];
			foreach ($head as &$h){
				$h = mb_check_encoding($h, 'UTF-8') ? $h : mb_convert_encoding($h, 'utf-8');
			}
			unset($res[1]);
			$arr = array();
			$num = 0;
			foreach ($res as $row){		
				foreach ($row as $key=>$val){
					$val = mb_check_encoding($val, 'UTF-8') ? $val : mb_convert_encoding($val, 'utf-8');
					$arr[$num][trim($head[$key])] = trim($val);			
				}
				$num++;
			}
		}
		return $arr;
	}else{
		return false;
	}
}


	
/**
 * 
 * 读取文件内容
 */
function readExcelFile($file,$type='excel'){
	$file_name = basename($file);
	//判断文件类型
	$temp = explode(".", $file_name);
	if($temp[1] == 'xls' || $type=='excel'){
		$res = excelToArray($file);
	}elseif ($temp[1] == 'csv' || $type=='csv'){
		$res = csvToArray($file);
	}
	return $res;
}


function implodeString($ids,$strArr){
    $arr = explode(',',$ids);
    $str = '';    
    foreach($arr as $k=>$v){
        if(isset($strArr[$v])){
            $str .=$strArr[$v].',';
        }
    }
    $str = trim($str,',');
    return $str;
}



/**
  *  函数返回管理员ID
 */ 

function getAdminId(){
    $session = getUserSession();
    return intval($session['id']);   
}

/**
* 返回前端登录的用户ID
*/ 
function getUserId(){
    $session = getUserSession();
    return intval($session['id']);      
}

/**
* 设置session登录信息
*/   
function setUserSession($val){
    if(GROUP_NAME=='admin'){
        session('admin',$val);    
    }else if(GROUP_NAME=='api'){
        session('user',$val);
    }
}

/**
*取 session 登录信息 
*/ 
function getUserSession(){
    if(GROUP_NAME=='admin'){
        return session('admin');    
    }else if(GROUP_NAME=='api'){
        return session('user');
    }       
}

/**
 * 判断报障是否有审核权限
 * 参数 
 * $curlStep  当前这条报障去到哪一步
 * $faultType 是机型报障，还是体验台报障
 */ 
 
 function isCanVerify($curlStep,$faultType){
    $admin = getUserSession();
    $roleId = $admin['roleId'];
    if('modelFault'==$faultType){
        $config = C('modle_fault_step');
    }elseif('showcaseFault'==$faultType){
        $config = C('showcase_fault_step');
    }
   if(is_array($config[$roleId]) && isset($config[$roleId][$curlStep])){
        return $config[$roleId][$curlStep];
   }else{
        return null;
   }
 }

/**
 * 取到地区名称 
 * $regionId : 地区ID，
 * $step ： 向前取多少级
 */ 
function getRegionName($regionId,$step){
    
    $regionList = F('region_list');
   
    $str = '';
    if(!empty($regionList)){
        $region = $regionList['l'][$regionId];
       
        $spid = $region['spid'];
        $name = $region['name'];
        $step = abs($step);
        $spid = trim($spid,'|');
        $arr = explode('|',$spid);
        $arr = array_slice($arr,-$step);
        
        foreach($arr as $k=>$v){
            if(!empty($v) && isset($regionList['l'][$v])){
                $str.=$regionList['l'][$v]['name'].'=》';
            }
        }
        $str = $str.$name;
    }
    return $str;
}

